'use strict';

const RouterService = require('../base');
const { Op } = require('sequelize');
const dayjs = require('dayjs');

class CouponService extends RouterService {
  static get modelName() {
    return 'Business.Coupon';
  }

  // 发放优惠券
  async distribute(data) {
    const { coupon_id, distribute_type, distribute_count, user_ids } = data;
    
    // 1. 验证优惠券是否存在且有效
    const coupon = await this.ctx.model.Business.Coupon.findByPk(coupon_id);
    if (!coupon) {
      throw new Error('优惠券不存在');
    }
    
    if (!coupon.is_enabled) {
      throw new Error('优惠券已禁用');
    }
    
    // if (coupon.remain_count < distribute_count) {
    //   throw new Error('优惠券剩余数量不足');
    // }
    
    // 2. 获取要发放的用户列表
    let users = [];
    if (distribute_type === 1) {
      // 发放给所有用户
      users = await this.ctx.model.Business.User.findAll({
        where: {
          status: 1 // 只发放给启用状态的用户
        }
      });
    } else if (distribute_type === 2) {
      // 发放给指定用户
      if (!user_ids || user_ids.length === 0) {
        throw new Error('请选择要发放的用户');
      }
      users = await this.ctx.model.Business.User.findAll({
        where: {
          id: {
            [Op.in]: user_ids
          },
          status: 1
        }
      });
    }
    
    if (users.length === 0) {
      throw new Error('没有找到符合条件的用户');
    }
    
    // 3. 创建事务
    const transaction = await this.ctx.model.transaction();
    
    try {
      // 4. 生成用户优惠券记录
      const userCoupons = [];
      const now = dayjs();
      
      for (const user of users) {
        for (let i = 0; i < distribute_count; i++) {
          const couponCode = this.generateCouponCode();
          userCoupons.push({
            user_id: user.id,
            coupon_id: coupon_id,
            coupon_code: couponCode,
            status: 0, // 未使用
            obtain_time: now.format('YYYY-MM-DD HH:mm:ss'),
            expire_time: coupon.end_time,
            creator: this.ctx.user ? this.ctx.user.id : 0,
            updater: this.ctx.user ? this.ctx.user.id : 0
          });
        }
      }
      
      // 5. 批量创建用户优惠券
      await this.ctx.model.Business.UserCoupon.bulkCreate(userCoupons, { transaction });
      
      // 6. 更新优惠券剩余数量
      const totalDistributed = users.length * distribute_count;
      await this.ctx.model.Business.Coupon.update({
        remain_count: this.ctx.model.Sequelize.literal(`remain_count + ${totalDistributed}`)
      }, {
        where: { id: coupon_id },
        transaction
      });
      
      await transaction.commit();
      
      return {
        success: true,
        message: `成功发放 ${totalDistributed} 张优惠券给 ${users.length} 个用户`,
        distributed_count: totalDistributed,
        user_count: users.length
      };
      
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
  
  // 生成优惠券码
  generateCouponCode() {
    const timestamp = Date.now().toString(36);
    const random = Math.random().toString(36).substr(2, 8);
    return `CP${timestamp}${random}`.toUpperCase();
  }
}

module.exports = CouponService; 